package com.example.demo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;
@Slf4j
public class JwtUtils {
    private static final long JWT_EXPIRATION = 60*60*1000;//设置token存活时间
    private static final String secretStr = "Le++o8NQWVXWo3+SJtAtnjBW9iA0OvPL0c0mMrol2fU=";//生成密钥
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretStr));//将密钥转换为字节数组

    /*
    生成令牌
     */
    public static String getToken(Map<String,Object> claim){
        String token = Jwts.builder().setClaims(claim)
                .setExpiration(new Date(System.currentTimeMillis()+JWT_EXPIRATION))//设置时间
                .signWith(key)//存储密钥
                .compact();//生成
        return token;
    }

    /**
     * 令牌校验
     */
    public static Claims parseToken(String token){
        JwtParser build = Jwts.parserBuilder().build();
        Claims claims=null;
        try {
            claims=build.parseClaimsJws(token).getBody();
        }catch (Exception e){
            log.info("令牌校验失败 token {}",token);
            return null;
        }
        return claims;
    }
}
